import { Component } from 'react';
import Child from './Child';
import Child1 from './Child1';

const MyAPI = {
  count: 0,
  subscribe (cb) {
    this.intervalId = setInterval ( () => {
      this.count += 1;
      cb ( this.count );
    }, 1000 )
  },
  unSubscribe () {
    clearInterval ( this.intervalId );
    this.reset ();
  },
  reset () {
    this.count = 0;
  }
}

export default class Parent extends Component {
  state = {
    count: 0,
  }
  componentDidMount () {
    MyAPI.subscribe ((currentCount) => {
      this.setState({
        count: currentCount,
      })
    })
  }
  componentWillUnmount () {
    // 页面销毁前清除本页面定时器
    MyAPI.unSubscribe();
  }
  render () {
    console.log("计时器组件（render）不断渲染，child不应该重复不必要的渲染");
    return (
      <div>
        Count: {this.state.count}
        <Child num={this.state.count} />
        <Child1 num='1' />
      </div>
    )
  }
}